package com.battery.minapp.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.battery.common.utils.BatteryJSONResult;
import com.battery.common.utils.Constants;
import com.battery.common.utils.http.HttpClientJSONUtil;
import com.battery.common.utils.security.Md5Utils;
import com.battery.system.domain.Prorely;
import com.battery.system.service.ISysConfigService;
import com.battery.system.service.battery.IProrelyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * WS-设备工具类
 */
@Component
public class WsDevUtils {


    @Autowired
    private IProrelyService prorelyService;


    @Autowired
    private ISysConfigService configService;

    public static WsDevUtils wsDevUtils;

    @PostConstruct
    public void init() {
        wsDevUtils = this;
    }

    /**
     * 检测设备是否在线
     *
     * @param sn
     * @return
     */
    public static BatteryJSONResult boxStatus(String sn) {
        Prorely prorely = wsDevUtils.prorelyService.selectBySn(sn);
        if (prorely == null) {
            return BatteryJSONResult.errorMsg("设备【" + sn + "】租借依据不存在");
        }
        String service = prorely.getService();
        Integer port = prorely.getPort() + 100;
        String url = "http://" + service + ":" + port + "/dev/boxStatus";

        String salt = Constants.ws_borrow_slat;
        JSONObject requestObj = new JSONObject();
        String before = sn + salt;
        requestObj.put("sn", sn);
        requestObj.put("sign", Md5Utils.hash(before));

        BatteryJSONResult result = null;
        try {
            String responseStr = HttpClientJSONUtil.postJSONUTF8(url, JSON.toJSONString(requestObj));
            result = JSON.parseObject(responseStr, BatteryJSONResult.class);
        } catch (Exception e) {
            e.printStackTrace();
            return BatteryJSONResult.errorMsg("设备【" + sn + "】请求");
        }
        if (result == null) {
            return BatteryJSONResult.errorMsg("设备不在线");
        }
        if (result.getCode().intValue() != 200) {
            return BatteryJSONResult.errorMsg("设备不在线");
        }
        return BatteryJSONResult.ok();
    }
}
